import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, Table, Avatar, Modal } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { router } from 'umi'
import { getAttrList, handleAttr, deleteAttr } from '@/services/goodCenter/attribute'

const { TextArea } = Input

const { Option } = Select

// 表头
const columns = [
  {
    title: '属性名称',
    dataIndex: 'attributeName',
    key: 'attributeName',
    align: 'center'
  },
  {
    title: '属性可选值',
    dataIndex: 'hasOptionalValue',
    key: 'hasOptionalValue',
    align: 'center'
  }
]

const Attribute = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [visible, setVisible] = useState(false)
  const [attrList, setAttrList] = useState([])
  const [hasOptionList, setHasOptionList] = useState([
    {
      id: '1',
      name: '开启'
    },
    {
      id: '0',
      name: '关闭'
    }
  ])
  const [modalType, setModalType] = useState(null)

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    let params = {
      attributeName: '',
      pageNo,
      pageSize
    }
    await getAttrLists(params)
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        attributeName: values.attributeName,
        pageNo,
        pageSize
      }
      await getAttrLists(params)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="属性名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('attributeName', {})
              (<Input placeholder="请输入属性名称" />)}
          </Form.Item>
        </Col>
      </Row>
    )
  }
  // 按钮处理
  const handleBtn = async type => {
    console.log(type)
    switch (type) {
      // 添加属性
      case 1:
        handleModal()
        setModalType('add')
        break
      // 编辑属性
      case 3:
        if (JSON.stringify(record) == "{}") return
        handleModal()
        setModalType('edit')
        break
      // 删除属性
      case 4:
        if (JSON.stringify(record) == "{}") return
        let params = {
          resPlatformAttributeVo: {
            id: record[0].id
          }
        }
        await deleteAttrs(params)
        break
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {

    }
  }
  // 获取属性列表
  const getAttrLists = async (params) => {
    let res = await getAttrList(params)
    if (res.code === '0') {
      setAttrList(res.data)
      setTotal(res.iTotalDisplayRecords)
    } else {
      alert(res.msg)
    }
  }
  // 操控弹出层
  const handleModal = () => {
    setVisible(!visible)
  }
  const handleOk = () => {
    form.validateFields(async (err, values) => {
      let params = {
        resPlatformAttributeVo: {
          attributeName: values.attributeName,
          hasOptionalValue: values.hasOptionalValue,
          id: '',
          resPlatformAttributeOptionalValues: [{
            id: '',
            status: values.hasOptionalValue,
            attributeValue: values.attributeValue
          }]
        }
      }
      if (values.hasOptionalValue === '0') params.resPlatformAttributeOptionalValues = []
      if (modalType === 'edit') params.status = '1'
      await handleAttrs(params)
    })
  }
  // 操控属性
  const handleAttrs = async (params) => {
    let res = await handleAttr(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }
  // 删除属性
  const deleteAttrs = async (params) => {
    let res = await deleteAttr(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={attrList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
      <Modal
        title="添加/编辑商品分类属性"
        visible={visible}
        onOk={handleOk}
        onCancel={handleModal}
      >
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item label="属性名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('attributeName', {})
                (<Input placeholder="请输入属性名称" />)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="是否开启可选值模式" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('hasOptionalValue', {})
                (<Select
                  style={{ width: '100%' }}
                  showSearch
                  filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                  placeholder="请选择"
                >
                  {hasOptionList && hasOptionList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
                </Select>)}
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label="可选值列表" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
              {getFieldDecorator('attributeValue', {})
                (<TextArea placeholder="请输入可选值列表" />)}
            </Form.Item>
          </Col>
        </Row>
      </Modal>
    </PageHeaderWrapper>
  )
}

export default Form.create()(Attribute)
